package cn.uhua.erp.pms.auth;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import cn.uhua.erp.pms.common.model.User;

public class CustomUserDetails implements UserDetails, CredentialsContainer {

    private String username;
    private String password;
    private List<String> authorities; // 存储多个角色，如 ["ROLE_USER", "ROLE_ADMIN"]
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    private boolean enabled;

    public CustomUserDetails(User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        // 每个Authority对象有getAuthority()方法获取权限字符串（如"ROLE_ADMIN"）
        this.authorities = user.getAuthorities().stream()
            .map(authority -> authority.getAuthority())  // 提取权限字符串
            .collect(Collectors.toList());  // 转换为List<String>
        this.accountNonExpired = !user.isAccountExpired();
        this.accountNonLocked = !user.isLocked();
        this.credentialsNonExpired = !user.isCredentialsExpired();
        this.enabled = user.isEnabled();
    }

    @Override
    public void eraseCredentials() {
        this.password = null;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 将每个角色转换为SimpleGrantedAuthority
        return authorities.stream()
                .map(authority -> new SimpleGrantedAuthority(authority))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {  
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
    
}
